package com.suning.park.web.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;

public class HttpUtil {

	private static Logger logger = LoggerFactory.getLogger(HttpUtil.class);


	public static String doPost(String url, Map<String, String> params) {
		StringBuffer sb = new StringBuffer();
		if (!params.isEmpty()) {
			for (Map.Entry<String, String> entry : params.entrySet()) {
				sb.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
			}
		}
		return sendRequestByPostGiveContentType(url,sb.toString(),"application/x-www-form-urlencoded","POST");

	}

	public static String doPost(String url, String param) {//application/x-www-form-urlencoded
		return sendRequestByPostGiveContentType(url,param,"application/x-www-form-urlencoded","POST");

	}




	public static String doGet(String url){
		String result = "";
		BufferedReader in = null;
		HttpURLConnection connection =null;
		try {
			URL u = new URL(url);
			connection =(HttpURLConnection) u.openConnection();
			connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			connection.setRequestMethod("GET");
			connection.setDoOutput(true); //http正文内，因此需要设为true, 默认情况下是false
			connection.setDoInput(true); //设置是否从httpUrlConnection读入，默认情况下是true
			connection.setUseCaches(false); //Post 请求不能使用缓存
			connection.setInstanceFollowRedirects(true); //URLConnection.setInstanceFollowRedirects是成员函数，仅作用于当前函数
			connection.setConnectTimeout(30000); //设置连接主机超时时间
			connection.setReadTimeout(30000); //设置从主机读取数据超时
			in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
			String line = in.readLine();
			while (line != null) {
				result += line;
				line = in.readLine();
			}
		} catch (Exception e) {
			// TODO: handle exception
		}finally{
			if (connection != null) {
				connection.disconnect();
			}
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return result;
	}


	public static String sendRequestByPostGiveContentType(String url, String paramStr,  String contentType,String method){
		logger.info("url:{}",url);
		logger.info("paramStr:{}",paramStr);
		String result = "";
		BufferedReader in = null;
		HttpURLConnection connection = null;
		OutputStream out = null;
		try {
			URL paostUrl = new URL(url);
			//参数配置
			connection = (HttpURLConnection) paostUrl.openConnection();
			connection.setRequestProperty("Content-Type", contentType);
			connection.setRequestMethod(method);
			connection.setDoOutput(true); //http正文内，因此需要设为true, 默认情况下是false
			connection.setDoInput(true); //设置是否从httpUrlConnection读入，默认情况下是true
			connection.setUseCaches(false); //Post 请求不能使用缓存
			connection.setInstanceFollowRedirects(true); //URLConnection.setInstanceFollowRedirects是成员函数，仅作用于当前函数
			connection.setConnectTimeout(30000); //设置连接主机超时时间
			connection.setReadTimeout(30000); //设置从主机读取数据超时

			//打开连接
			out = connection.getOutputStream();
			out.write(paramStr.getBytes());
			in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
			String line = in.readLine();
			while (line != null) {
				result += line;
				line = in.readLine();
			}
		} catch (Exception e) {
			logger.error("post请求发生异常", e);
		} finally {
			try {
				if (out != null) {
					out.close();
				}
				if (in != null) {
					in.close();
				}
				if (connection != null) {
					connection.disconnect();
				}
			} catch (IOException e) {
				logger.error("error", e);
			}
		}
		logger.info("请求返回结果：{}",result);
		return result;

	}

	/**
	 * @param url 请求的新接口路径
	 * @param method 请求方式（post）
	 * @return
	 * @throws IOException
	 */
	public static String getResultMessage(String url, String params, String method) throws IOException {
		String re = "";
		URL sendurl = new URL(url);
		HttpURLConnection httpUrl = (HttpURLConnection) sendurl.openConnection();
		httpUrl.setDoInput(true);
		httpUrl.setDoOutput(true);
		httpUrl.setUseCaches(false);
		httpUrl.setConnectTimeout(300 * 1000);
		httpUrl.setReadTimeout(300 * 1000);
		httpUrl.setInstanceFollowRedirects(true);
		httpUrl.setRequestMethod(method);//POST||GET

		//         logger.info("put-url:"+url+"\n"+httpUrl.getURL()+params+"\n");
		logger.info("----------------------");
		logger.info("url:" + url);
		logger.info("requestmethod:  " + method);
		logger.info("params: " + params);
		httpUrl.connect();
		httpUrl.getOutputStream().write(params.getBytes("UTF-8"));
		PrintWriter out = new PrintWriter(httpUrl.getOutputStream());
		out.flush();
		out.close();
		BufferedReader in = new BufferedReader(new InputStreamReader(httpUrl.getInputStream(), "UTF-8"));
		while (in.ready()) {
			re = re + in.readLine();
			httpUrl.disconnect();
			//	         logger.debug("POST SUBMIT TO SERVICE reString: "+ re);
		}
		return re;

	}
}